// ============================================================================
// WeiboData 实体定义
// ============================================================================

import {
  Entity,
  PrimaryColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
  BeforeInsert
} from 'typeorm'
import { JsonTransformer } from '../transformers/json.transformer'
import { v4 as uuidv4 } from 'uuid'

/**
 * 微博数据实体
 */
@Entity('weibo_data')
@Index(['weiboId'], { unique: true })
@Index(['userId'])
@Index(['isRepost'])
@Index(['createdAt'])
export class WeiboData {
  @PrimaryColumn({ type: 'varchar' })
  id: string

  @Column({ name: 'weibo_id', unique: true, type: 'varchar' })
  weiboId: string

  @Column({ type: 'text' })
  text: string

  @Column({ name: 'user_id', type: 'varchar' })
  userId: string

  @Column({ name: 'user_nickname', type: 'varchar' })
  userNickname: string

  @Column({ name: 'user_avatar', nullable: true, type: 'varchar' })
  userAvatar?: string

  @Column({ nullable: true, type: 'varchar' })
  source?: string

  @Column({ name: 'reposts_count', type: 'integer', default: 0 })
  repostsCount: number

  @Column({ name: 'comments_count', type: 'integer', default: 0 })
  commentsCount: number

  @Column({ name: 'likes_count', type: 'integer', default: 0 })
  likesCount: number

  @Column({
    type: 'text',
    nullable: true,
    transformer: new JsonTransformer()
  })
  images?: string[]

  @Column({
    type: 'text',
    nullable: true,
    transformer: new JsonTransformer()
  })
  video?: any

  @Column({ nullable: true, type: 'varchar' })
  location?: string

  @Column({ name: 'is_repost', type: 'boolean', default: false })
  isRepost: boolean

  @Column({ name: 'original_weibo_id', nullable: true, type: 'varchar' })
  originalWeiboId?: string

  @Column({ name: 'published_at', type: 'datetime' })
  publishedAt: Date

  @Column({ name: 'task_id', nullable: true, type: 'varchar' })
  taskId?: string

  @Column({
    type: 'text',
    nullable: true,
    transformer: new JsonTransformer()
  })
  metadata?: any

  @CreateDateColumn({ name: 'created_at' })
  createdAt: Date

  @UpdateDateColumn({ name: 'updated_at' })
  updatedAt: Date

  @BeforeInsert()
  generateId() {
    if (!this.id) {
      this.id = uuidv4()
    }
  }

  /**
   * 检查是否为转发微博
   */
  isRepostWeibo(): boolean {
    return this.isRepost
  }

  /**
   * 获取互动总数
   */
  getTotalInteractions(): number {
    return this.repostsCount + this.commentsCount + this.likesCount
  }

  /**
   * 检查是否包含图片
   */
  hasImages(): boolean {
    return !!(this.images && this.images.length > 0)
  }

  /**
   * 检查是否包含视频
   */
  hasVideo(): boolean {
    return this.video !== null && this.video !== undefined
  }

  /**
   * 获取文本长度
   */
  getTextLength(): number {
    return this.text.length
  }

  /**
   * 转换为微博数据格式（向后兼容）
   */
  toWeiboDataFormat() {
    return {
      id: this.id,
      weiboId: this.weiboId,
      text: this.text,
      userId: this.userId,
      userNickname: this.userNickname,
      userAvatar: this.userAvatar,
      source: this.source,
      repostsCount: this.repostsCount,
      commentsCount: this.commentsCount,
      likesCount: this.likesCount,
      images: this.images,
      video: this.video,
      location: this.location,
      isRepost: this.isRepost,
      originalWeiboId: this.originalWeiboId,
      publishedAt: this.publishedAt,
      taskId: this.taskId,
      metadata: this.metadata,
      createdAt: this.createdAt,
      updatedAt: this.updatedAt
    }
  }

  /**
   * 从微博数据创建实体
   */
  static fromWeiboData(data: any): WeiboData {
    const weibo = new WeiboData()
    weibo.id = data.id || uuidv4()
    weibo.weiboId = data.weiboId
    weibo.text = data.text
    weibo.userId = data.userId
    weibo.userNickname = data.userNickname
    weibo.userAvatar = data.userAvatar
    weibo.source = data.source
    weibo.repostsCount = data.repostsCount || 0
    weibo.commentsCount = data.commentsCount || 0
    weibo.likesCount = data.likesCount || 0
    weibo.images = data.images
    weibo.video = data.video
    weibo.location = data.location
    weibo.isRepost = data.isRepost || false
    weibo.originalWeiboId = data.originalWeiboId
    // 安全处理日期转换，避免无效日期
    if (data.publishedAt) {
      const date = new Date(data.publishedAt)
      weibo.publishedAt = isNaN(date.getTime()) ? new Date() : date
    } else {
      weibo.publishedAt = new Date()
    }
    weibo.taskId = data.taskId
    weibo.metadata = data.metadata
    return weibo
  }


}
